import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Users, UsersDocument } from 'src/db/schemas/users.schema';
import { Model, startSession } from 'mongoose';
import { CreateUserDto } from './dto/create-user.dto';
import { success } from 'src/common/responses';
import { DeleteDto } from 'src/dto/delete.dto';
import { HttpErrorException } from 'src/common/exceptions';
import { successFindAll } from 'src/common/responses';

@Injectable()
export class UsersService {
  constructor(
    @InjectModel(Users.name) private usersModel: Model<UsersDocument>,
  ) { }

  async addOne(createUserDto: CreateUserDto) {
    const session = await this.usersModel.startSession()
    try {
      session.startTransaction()
      const createdUser = new this.usersModel(createUserDto);
      await createdUser.save({
        session
      });
      await session.commitTransaction()
      return success();
    } catch (error: any) {
      await session.abortTransaction()
      throw new HttpErrorException(new Error(error).message);
    } finally {
      session.endSession()
    }
  }

  async getAll() {
    try {
      const data = await this.usersModel.find().exec();
      const total = await this.usersModel.count().exec();
      return successFindAll({
        data,
        total
      });
    } catch (error: any) {
      throw new HttpErrorException(new Error(error).message);
    }
  }

  async delete(deleteDto: DeleteDto) {
    const { ids } = deleteDto;
    try {
      await Promise.all(
        ids.map((_id) => this.usersModel.deleteMany({ _id })),
      );
      return success();
    } catch (error: any) {
      throw new HttpErrorException(new Error(error).message);
    }
  }
}
